package com.example.module_main


import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.manager.DownloadManager
import com.example.lib_common.Router
import com.example.lib_common.base.BaseActivity
import com.example.module_main.databinding.ActivityMainBinding
import com.example.module_main.dialog.AppUpdateDialog
import com.example.module_main.viewmodel.MainViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = Router.Ui.MainActivity)
class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_main
    private lateinit var mMotoCircleFragment:Fragment
    private lateinit var mClubFragment: Fragment
    private lateinit var mMallFragment: Fragment
    private lateinit var mMineFragment: Fragment
    private lateinit var mMessageFragment: Fragment
    companion object{
        private const val MY_CAR_FRAGMENT = "myCar"
        private const val MOTOR_CIRCLE_FRAGMENT = "friends"
        private const val MOTOR_CLUB_FRAGMENT = "club"
        private const val MOTOR_CLUB_FRAGMENT_CHECKING = "club_checking"
        private const val MOTOR_CLUB_FRAGMENT_NOT_JOINED = "club_not_joined"
        private const val MINE_FRAGMENT = "mine"
        private const val MALL_FRAGMENT = "mall"
        private const val MESSAGE_FRAGMENT = "message"

        const val MESSAGE_REGISTRATION_ID = "com.jczy.cyclone.MESSAGE_REGISTRATION_ID"
    }
    private val mViewModel:MainViewModel by viewModels()
    override fun initData() {
//        mViewModel.checkUpDate()
    }

    override fun initView() {
        mClubFragment = ARouter.getInstance().build(Router.Ui.ClubFragment).navigation() as Fragment
        mMotoCircleFragment = ARouter.getInstance().build(Router.Ui.MotocircleFragment).navigation() as Fragment
        mMallFragment = ARouter.getInstance().build(Router.Ui.MallFragment).navigation() as Fragment
        mMessageFragment = ARouter.getInstance().build(Router.Ui.MessageFragment).navigation() as Fragment
        mMineFragment = ARouter.getInstance().build(Router.Ui.MineFragment).navigation() as Fragment
        navToFragment(R.id.nav_motor_circle)
        mBinding.navMotorCircle.isChecked = true
    }

    override fun initListener() {
        //版本更新
//        mViewModel._appUpdateLiveData.observe(this){updateModel->
//            if (updateModel != null){
//                if (updateModel.latestVersion.isEmpty()
//                    || updateModel.downloadUrl.isNullOrEmpty()
//                    || updateModel.latestVersion == "1.0.0"
//                    ){
//                    return@observe
//                }
//            }
//            val new = updateModel.latestVersion.split(".")
//            if (new.isEmpty() || new.size != 3) return@observe
//            val current = "1.0.0".split(".")
//            val needUpdate = isNeedUpdate(new, current)
//            if (!needUpdate) return@observe
//            if (updateModel.forceUpGrade != 2 || System.currentTimeMillis() - AppMMKV.lastLaunchTime > 10 * 60 * 1000L){
////                AppUpdateDialog(
////                    title = String.format("最新版本%s升级说明", updateModel.latestVersion),
////                    message = updateModel.message,
////                    updateModel.forceUpGrade != 2
////                ) {
////                    forceUpdate(updateModel!!.downloadUrl!!, updateModel.latestVersion)
////                }.show(supportFragmentManager)
////                AppMMKV.lastLaunchTime = System.currentTimeMillis()
//            }
//        }
        mBinding.rgBottom.setOnCheckedChangeListener { _, i ->
            navToFragment(i)
        }
    }
    /**
     * 下载app并安装
     */
    private fun forceUpdate(downloadUrl: String, latestVersion: String) {
        val manager = DownloadManager.Builder(this).run {
            apkUrl(downloadUrl)
            apkName("app_new_version.apk")
            enableLog(false)
            smallIcon(com.example.lib_common.R.mipmap.app_icon)
            showBgdToast(true)
            showNotification(true)
            apkVersionName(latestVersion)
            build()
        }
        manager.download()
    }
    private fun navToFragment(id:Int) {
        val bt = supportFragmentManager.beginTransaction()
        hideCurrentFragment(bt)
        when (id) {
            R.id.nav_motor_club -> {
                if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT_NOT_JOINED)?.isAdded != true) {
                    bt.add(
                        R.id.fragment_container,
                        mClubFragment,
                        MOTOR_CLUB_FRAGMENT_NOT_JOINED
                    )
                } else {
                    bt.show(mClubFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }

            R.id.nav_motor_circle -> {
                if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isAdded == true) {
                    bt.show(mMotoCircleFragment)
                } else {
                    bt.add(
                        R.id.fragment_container,
                        mMotoCircleFragment,
                        MOTOR_CIRCLE_FRAGMENT
                    ) //tag标记
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }

            R.id.nav_message -> {
                if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMessageFragment, MESSAGE_FRAGMENT)
                } else {
                    bt.show(mMessageFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }

            R.id.nav_motor_mall -> {
                if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMallFragment, MALL_FRAGMENT)
                } else {
                    bt.show(mMallFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }

            R.id.nav_mine -> {
                if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isAdded != true) {
                    bt.add(R.id.fragment_container, mMineFragment, MINE_FRAGMENT)
                } else {
                    bt.show(mMineFragment)
                }
                bt.commitAllowingStateLoss()
                updateUnreadMessage()
            }
        }
    }
    /**
     * 获得未读消息红点更新显示
     */
    private fun updateUnreadMessage() {

    }

    private fun hideCurrentFragment(bt: FragmentTransaction) {
        if (supportFragmentManager.findFragmentByTag(MOTOR_CIRCLE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMotoCircleFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MOTOR_CLUB_FRAGMENT_NOT_JOINED)?.isVisible == true) {
            bt.hide(mClubFragment)
        }

        if (supportFragmentManager.findFragmentByTag(MALL_FRAGMENT)?.isVisible == true) {
            bt.hide(mMallFragment)
        }

        if (supportFragmentManager.findFragmentByTag(MESSAGE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMessageFragment)
        }
        if (supportFragmentManager.findFragmentByTag(MINE_FRAGMENT)?.isVisible == true) {
            bt.hide(mMineFragment)
        }
    }
    /**
     * 判断是否需要更新
     */
    private fun isNeedUpdate(new: List<String> , current: List<String>):Boolean{
        if (new[0].toInt() > current[0].toInt()){
            return true
        }else if (new[0].toInt() < current[0].toInt()){
            return false
        }
        if (new[1].toInt() > current[1].toInt()){
            return true
        }else if (new[1].toInt() < current[1].toInt()){
            return false
        }
        if (new[2].toInt() > current[2].toInt()){
            return true
        }else if (new[2].toInt() < current[2].toInt()){
            return false
        }
        return false
    }
}